const app = getApp();
import { reqUserInfo, updateInitWeight, updateTargetWeight, updateCurrentWeight } from '../../../api/user';
import * as echarts from 'echarts';
import { ComponentWithStore } from 'mobx-miniprogram-bindings';
import { userStore } from '../../../stores/userstore';
import { setStorage } from '../../../utils/storage';

ComponentWithStore({
  data: {
    value: 25,
    gradientColor: {
      '0%': '#ffd01e',
      '100%': '#ee0a24',
    },
    unit: 'kg',
    unitLabel: '千克/斤',
    weightStatus: '-',
    weightDifference: (50 - 45).toFixed(2),
    progressPercentage: (((50 - 45) / (50 - 44)) * 100).toFixed(2),
    targetWeight: 44,
    initialWeight: 50,
    currentWeight: 45,
    initialDate: '2024.10.1',
    currentDate: '2024.10.3',
    targetDate: '2024.10.30',
    weightRecords: [],
    ec: {
      lazyLoad: true,
    },
  },
  storeBindings: {
    store: userStore,
    fields: ['userInfo'],
    actions: ['setUserInfo'],
  },

  methods: {
    async upInit(weight) {
      const res = await updateInitWeight(weight);
      console.log(res);
    },
    async upTarget(weight) {
      const res = await updateTargetWeight(weight);
      console.log(res);
    },
    async upCurrent(weight) {
      const res = await updateCurrentWeight(weight);
      console.log(res);
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}.${month}.${day}`;
    },

    async getWeightInfo() {
      const { data } = await reqUserInfo();
      console.log(data);
      const initialDate = new Date(data.createdAt);
      const now = new Date();

      const formattedInitialDate = this.formatDate(initialDate);
      const formattedCurrentDate = this.formatDate(now);

      setStorage('userInfo', data);
      this.setUserInfo(data);

      this.setData({
        targetWeight: data.targetWeight,
        initialWeight: data.initialWeight,
        currentWeight: data.currentWeight,
        initialDate: formattedInitialDate,
        currentDate: formattedCurrentDate,
        targetDate: '2024-12-30',
      });

      // 更新图表数据
      this.updateChart();
    },

    toggleUnit() {
      let { unit, currentWeight, initialWeight, targetWeight } = this.data;
      const newUnit = unit === 'kg' ? '斤' : 'kg';
      const conversionRate = newUnit === 'kg' ? 0.5 : 2;

      this.setData({
        unit: newUnit,
        unitLabel: newUnit === 'kg' ? '斤/公斤' : '公斤/斤',
        currentWeight: (currentWeight * conversionRate).toFixed(2),
        initialWeight: (initialWeight * conversionRate).toFixed(2),
        targetWeight: (targetWeight * conversionRate).toFixed(2),
      });
      this.calculateWeightDifference();
      this.calculateProgress();
    },

    calculateWeightDifference() {
      const { currentWeight, initialWeight } = this.data;
      const weightDifference = currentWeight - initialWeight;
      const weightStatus = weightDifference < 0 ? '-' : '+';

      this.setData({
        weightDifference: Math.abs(weightDifference).toFixed(2),
        weightStatus,
      });
    },

    calculateProgress() {
      const { initialWeight, currentWeight, targetWeight } = this.data;
      const totalDifference = initialWeight - targetWeight;
      const currentDifference = initialWeight - currentWeight;
      const progressPercentage = (currentDifference / totalDifference) * 100;
      this.setData({
        progressPercentage: Math.min(Math.max(progressPercentage, 0), 100).toFixed(2),
      });
    },

    recordWeight() {
      wx.showModal({
        title: '请输入体重',
        content: '',
        editable: true,
        success: (res) => {
          if (res.confirm) {
            const newWeight = parseFloat(res.content);
            const newDate = this.getCurrentDate();
            const newRecord = {
              date: newDate,
              weight: newWeight,
            };

            const weightRecords = wx.getStorageSync('weightRecords') || [];
            const updatedRecords = [...weightRecords, newRecord].slice(-7); // 只保留最近7条记录
            wx.setStorageSync('weightRecords', updatedRecords);

            this.setData({
              currentWeight: newWeight,
              currentDate: newDate,
              weightRecords: updatedRecords,
            });

            this.calculateWeightDifference();
            this.calculateProgress();
            this.updateChart();
          }
        },
      });
    },

    editWeight(e) {
      const type = e.currentTarget.dataset.type;
      wx.showModal({
        title: `编辑${type === 'initial' ? '初始' : type === 'current' ? '当前' : '目标'}体重`,
        content: '',
        editable: true,
        success: (res) => {
          if (res.confirm) {
            const newWeight = parseFloat(res.content);
            const newDate = this.getCurrentDate();

            if (type === 'initial') {
              this.upInit(newWeight);
              this.setData({ initialWeight: newWeight, initialDate: newDate });
            } else if (type === 'current') {
              this.upCurrent(newWeight);
              this.setData({ currentWeight: newWeight, currentDate: newDate });
            } else if (type === 'target') {
              this.upTarget(newWeight);
              this.setData({ targetWeight: newWeight, targetDate: newDate });
            }

            this.calculateWeightDifference();
            this.calculateProgress();
            this.updateChart();
          }
        },
      });
    },

    setChartOptions(chart) {
      const { weightRecords } = this.data;
      const dates = weightRecords.map((record) => record.date);
      const weights = weightRecords.map((record) => record.weight);

      chart.setOption({
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            formatter: (value) => value.split('.').slice(1).join('/'), // 仅显示月/日
          },
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: weights,
            type: 'line',
            smooth: true,
            lineStyle: {
              color: '#6bc1c2',
              width: 3,
            },
            areaStyle: {
              color: 'rgba(107, 193, 194, 0.2)',
            },
            label: {
              show: true,
              position: 'top',
            },
          },
        ],
      });
    },

    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}.${month}.${day}`;
    },

    updateChart() {
      const ecComponent = this.selectComponent('#lineChart');
      if (ecComponent) {
        ecComponent.init((canvas, width, height, dpr) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr,
          });
          this.chart = chart;
          this.setChartOptions(chart); // 使用实际数据更新图表
        });
      }
    },

    initChart(canvas, width, height, dpr) {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr,
      });
      this.chart = chart;
      this.setChartOptions(chart); // 使用预设数据初始化图表
    },

    onLoad() {
      this.getWeightInfo();
  
      // 使用预设数据初始化图表
      const defaultRecords = this.fillDefaultRecords([  ]);
      this.setData({
        weightRecords: defaultRecords,
      });
  
      // 计算初始的体重差异和进度
      this.calculateWeightDifference();
      this.calculateProgress();
    },

    onReady() {
      // 页面渲染完成后初始化折线图
      this.initChart();
    },
  
    fillDefaultRecords(records) {
      const filledRecords = [...records];
      const today = new Date();
      while (filledRecords.length < 7) {
        const defaultDate = new Date(today);
        defaultDate.setDate(today.getDate() - (7 - filledRecords.length));
        filledRecords.unshift({
          date: this.formatDate(defaultDate),
          weight: this.data.initialWeight, // 用初始体重作为默认值
        });
      }
      return filledRecords.slice(-7); // 确保只保留最近7条记录
    }

  },
});